﻿Imports TagLib
Imports System.ComponentModel

Public Class Taggable
    Implements INotifyPropertyChanged


    Public Property Title As String
    Public Property Filepath As String
    Public Property Artist As String
    Public Property Year As String
    Public Property Track As String
    Public Property Album As String

    Public ReadOnly Property Filename As String
        Get
            Return Filepath.Split(CChar("\")).Last
        End Get
    End Property

    Public Sub LoadTags()
        Dim f = TagLib.File.Create(Filepath)

        Title = f.Tag.Title
        Artist = If(f.Tag.AlbumArtists.Count > 0, f.Tag.AlbumArtists(0), If(f.Tag.Artists.Count > 0, f.Tag.Artists(0), String.Empty))
        Album = f.Tag.Album
        Track = f.Tag.Track.ToString
        Year = f.Tag.Year.ToString

        f.Dispose()
    End Sub


    Public Sub WriteTags()
        Dim f = TagLib.File.Create(Filepath)


        If Not String.IsNullOrWhiteSpace(Title) Then
            f.Tag.Title = Title
        End If

        If Not String.IsNullOrWhiteSpace(Album) Then
            f.Tag.Album = Album
        End If

        If Not String.IsNullOrWhiteSpace(Artist) Then
            f.Tag.Artists = {Artist}
            f.Tag.AlbumArtists = {Artist}
        End If

        If Not String.IsNullOrWhiteSpace(Track) Then
            Dim t As UInteger = 0
            UInteger.TryParse(Track, t)
            f.Tag.Track = t
        End If

        If Not String.IsNullOrWhiteSpace(Year) Then
            Dim t As UInteger = 0
            UInteger.TryParse(Year, t)
            f.Tag.Year = t
        End If

        f.Save()
        f.Dispose()
    End Sub

    Public Event PropertyChanged(ByVal sender As Object, ByVal e As System.ComponentModel.PropertyChangedEventArgs) Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged
    Public Sub OnPropertyChanged(ByVal name As String)
        RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(name))
    End Sub

    Public Sub Notify()
        OnPropertyChanged("Artist")
        OnPropertyChanged("Album")
        OnPropertyChanged("Track")
        OnPropertyChanged("Title")
        OnPropertyChanged("Year")
    End Sub
End Class
